﻿using SvgApplication.Authorization;
using SvgApplication.Controllers;
using SvgApplication.Data.Implementation;
using SvgApplication.Data.Model;
using SvgApplication.Data.Model.Interfaces;
using SvgApplication.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SvgApplication.Web.Controllers
{
    [RoleAuthorizationAttribute(Modules = UserRoles.Admin)]
    public class UserController : AuthorizationControllerBase
    {

        IUserRepository userRepository;

        public UserController()
            : this(new UserRepository())
        {

        }

        public UserController(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }



        //
        // GET: /Admin/

        public ActionResult Index()
        {
            return View("List");
        }


        public ActionResult List()
        {
            return View();
        }

        public ActionResult Create()
        {
            //<label class="error">@ViewBag.Error</label>

            return View(new UserUIModel());
        }

        [HttpPost]
        public ActionResult Create(UserUIModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    userRepository.Create(new User()
                    {
                        Username = model.Username,
                        Password = model.Password,
                        Role = (byte)UserRoles.RegularUser,
                        Blocked = false
                    });

                    return RedirectToAction("List");
                }
                catch (Exception ex)
                {
                    AddError(ex.Message);
                }
            }
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            var existingShipment = userRepository.GetById(id);
            UserUIDeleteModel userUiModel = new UserUIDeleteModel()
            {
                Username = existingShipment.Username,
                Id = existingShipment.Id,
            };
            return View(userUiModel);
        }

        [HttpPost]
        public ActionResult Delete(UserUIDeleteModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    userRepository.Delete(model.Id);
                    return RedirectToAction("List");
                }
                catch (Exception ex)
                {
                    AddError(ex.Message);
                }
            }
            return View(model);
        }


        public ActionResult Edit(int id)
        {
            var existingUser = userRepository.GetById(id);

            //get the possible states

            UserUIModel userUImodel = new UserUIModel()
            {
                Username = existingUser.Username,
                Id = existingUser.Id,
                Password = existingUser.Password,

            };

            return View(userUImodel);
        }

        //private List<SelectListItem> BuildStateList(Shipment existingShipment)
        //{
        //    var selectList = GetSelectList();
        //    //select the current state
        //    var currentItem = selectList.First(p => p.Value == existingShipment.State.ToString());
        //    currentItem.Selected = true;
        //    return selectList;
        //}

        [HttpPost]
        public ActionResult Edit(UserUIModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    userRepository.Update(new User()
                    {
                        Username = model.Username,
                        Password = model.Password,
                        Id = model.Id,
                    });

                    return RedirectToAction("List");
                }
                catch (Exception ex)
                {
                    AddError(ex.Message);
                }
            }
            else
            {
                AddError("invalid model");
            }
            return Edit(model.Id);
        }

        [HttpGet]
        public ActionResult BlockUser(int id, bool blockedState)
        {
            var existingUser = userRepository.GetById(id);

            return View(new BlockUserModel() { UserId = id, Username = existingUser.Username, BlockedState = existingUser.Blocked });
        }

        [HttpPost]
        public ActionResult BlockUser(BlockUserModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    userRepository.UpdateBlockedState(model.UserId, !model.BlockedState, model.Reason);
                    return RedirectToAction("List");
                }
                catch (Exception ex)
                {
                    AddError(ex.Message);
                }
            }
            else
            {
                AddError("invalid model");
            }
            return View(model);
        }

        //[HttpGet]
        //public JsonResult Search(string trackingNumber)
        //{
        //    Shipment result = userRepository.GetByTrackingNumber(trackingNumber);
        //    if (result == null)
        //    {
        //        return null;
        //    }
        //    ShipmentUISearchModel uiResultModel = new ShipmentUISearchModel()
        //    {
        //        Id = result.Id,
        //        State = ((ShipmentStates)result.State).ToString(),
        //        TrackingNumber = result.TrackingNumber,
        //        StartTimestamp = FormatDateTime(result.StartTimestamp),
        //        LastUpdateTimestamp = FormatDateTime(result.LastUpdatedTimestamp)
        //    };
        //    return Json(uiResultModel, JsonRequestBehavior.AllowGet);
        //}


        #region private
        //private List<SelectListItem> GetSelectList()
        //{
        //    List<SelectListItem> list = new List<SelectListItem>();
        //    var values = Enum.GetValues(typeof(ShipmentStates));
        //    foreach (var item in values)
        //    {
        //        AddItem(list, item);
        //        //switch ((ShipmentStates)item)
        //        //{
        //        //    case ShipmentStates.Finalized:
        //        //        AddItem(list, item);
        //        //        break;
        //        //    case ShipmentStates.OnGoing:
        //        //        break;
        //        //    case ShipmentStates.Started:
        //        //        break;
        //        //}
        //    }
        //    return list;
        //}

        #endregion
        private static void AddItem(List<SelectListItem> list, object item)
        {
            list.Add(new SelectListItem() { Text = item.ToString(), Value = ((byte)item).ToString(), Selected = false });
        }

        [HttpGet]
        public object GetGridModel(string sidx, string sord, int page, int rows, bool _search, string searchField = "", string searchOper = "", string searchString = "")
        {
            int total = 0;
            var userList = userRepository.Get(out total, page, rows, null, sidx).ToList();
            List<UserGridModel> gridModel = new List<UserGridModel>();
            foreach (var item in userList)
            {
                gridModel.Add(new UserGridModel()
                {
                    Id = item.Id,
                    Username = item.Username,
                    Blocked = item.Blocked,
                    BlockReason = item.BlockReason
                });
            }
            var jqgridData = TojQgridFormat(gridModel, page, rows, total);
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jqgridData, Newtonsoft.Json.Formatting.None);
            return jsonString;
        }

        internal JqGridUIModel TojQgridFormat(IEnumerable<object> list, int page, int pageSize, int totalRecords)
        {
            var pageIndex = page - 1;
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            return new JqGridUIModel
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = list.ToArray()
            };
        }

        private string FormatDateTime(DateTime? dt)
        {
            if (dt.HasValue)
            {
                return dt.Value.ToString("yyyy-MM-dd hh:mm:ss");
            }
            return "none";
        }
        private void AddError(string message)
        {
            ViewBag.Error = message;
            ViewData["Error"] = message;
        }

    }

    public class SearchObj
    {
        public string TrackingNumber { get; set; }
    }
}
